<template>
  <div class="container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <!-- 选择地市 -->
      <el-select v-model="Prefecture" placeholder="选择地市" class="search-item">
        <el-option
          v-for="item in Prefectures"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <!-- 选择区县 -->
      <el-select v-model="city" placeholder="选择区县" class="search-item">
        <el-option
          v-for="item in citys"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <!-- 任务类型 -->
      <el-select v-model="task" placeholder="任务类型" class="search-item">
        <el-option
          v-for="item in tasks"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <!-- 任务状态 -->
      <el-select v-model="state" placeholder="任务状态" class="search-item">
        <el-option
          v-for="item in states"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      
      <!-- 第二行搜索条件 -->
      <div class="search-row">
        <!-- 通信塔类型 -->
        <el-select v-model="type" placeholder="通信塔类型" class="search-item">
          <el-option
            v-for="item in towerTypeList"
            :label="item.towerType.typeName"
            :value="item.towerType.id"
          />
        </el-select>
        <el-input v-model="input" class="search-input" placeholder="输入任务名称" />
        <el-button  style="background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" class="search-btn" @click="filterUser">查询</el-button>
        <el-button  style="background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" class="search-btn" @click="newUser" v-if="hasPermission(authStore.permissions,11)">新建巡视任务</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table 
        :data="displayedData" 
        style="width: 100%"
        stripe
        highlight-current-row
        @row-click="handleRowClick"
        class="auto-width-table"
      >
        <el-table-column label="序号"  textAlign="center">
          <template #default="{ row, $index }">
            <span v-if="row.inspectionTask">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
            <span v-else style="color:black;opacity: 0;">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="role.inspectionTask.taskName" label="任务名称"  textAlign="center">
          <template #default="{ row }">
            <span class="table-text">{{ row.inspectionTask?.taskName }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="role.inspectionTask.taskType" label="任务类型"  textAlign="center">
          <template #default="{ row }">
            <span class="table-text">{{ row.inspectionTask?.taskType }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="role.towerType.typeName" label="通信塔类型"  textAlign="center">
          <template #default="{ row }">
            <span class="table-text">{{ row.towerType?.typeName }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="role.tower.city" label="地市"  textAlign="center">
          <template #default="{ row }">
            <span class="table-text">{{ row.tower?.city }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="role.tower.county" label="区县"  textAlign="center">
          <template #default="{ row }">
            <span class="table-text">{{ row.tower?.county }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="role.user.name" label="巡视人员" textAlign="center">
          <template #default="{ row }">
            <span class="table-text">{{ row.user?.name }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="role.inspectionTask.taskStatus" label="任务状态"  textAlign="center">
          <template #default="{ row }">
            <el-tag  v-if="row.inspectionTask" :type="getStatusTagType(row.inspectionTask?.taskStatus)">
              {{ row.inspectionTask?.taskStatus }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="role.inspectionTask.inspectionDate" label="巡视时间"  textAlign="center">
          <template #default="{ row }">
            <span class="table-text">{{ row.inspectionTask?.inspectionDate }}</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作"  textAlign="center">
          <template #default="{ row }">
            <div v-if="row.inspectionTask" class="action-buttons">
              <el-button 
                v-if="row.inspectionTask.taskStatus === '未下发' && hasPermission(authStore.permissions,12)" 
                link type="primary" 
                size="small" 
                @click.stop="changeTask(row)"
                style="color: rgb(110, 78, 208);"
              >
                编辑
              </el-button>
              <el-button 
                v-if="row.inspectionTask.taskStatus === '执行失败' &&  hasPermission(authStore.permissions,14)" 
                link type="primary" 
                size="small" 
                @click.stop="handleClick(row.id)"
                style="color: rgb(110, 78, 208);"
              >
                重新执行
              </el-button>
              <el-button 
                v-if="hasPermission(authStore.permissions,13)"
                link 
                type="danger" 
                size="small" 
                :disabled="row.inspectionTask.taskStatus == '待执行'||row.inspectionTask.taskStatus == '执行中'  " 
                @click.stop="showDialog(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, jumper"
        :background="true"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新建任务对话框 -->
    <el-dialog 
      v-model="visible" 
      :show-close="false" 
      width="800px"
      class="custom-dialog"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="dialog-header">
          <h3>巡视任务基本信息</h3>
          <div class="header-divider"></div>
        </div>
      </template>

      <!-- 输入框区域 -->
      <div class="form-container">
  <div class="form-item">
    <div class="form-label">
      <span class="required">*</span>所属机构:
    </div>
    <div class="form-field">
      <el-select v-model="OrganizationName" :class="{'invalid': djiUserErrors.OrganizationName}" placeholder="请选择所属机构" class="form-input" filterable
        clearable>
        <el-option
          v-for="item in transformedSecondaryOrganizationList"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <p v-if="djiUserErrors.OrganizationName" class="error-text">所属机构不能为空</p>
    </div>
  </div>

  <div class="form-item">
    <div class="form-label">
      <span class="required">*</span>任务类型:
    </div>
    <div class="form-field">
      <el-select v-model="taskAdd" :class="{'invalid': djiUserErrors.taskAdd}" placeholder="请选择任务类型" class="form-input" filterable
        clearable>
        <el-option
          v-for="item in tasks"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <p v-if="djiUserErrors.taskAdd" class="error-text">任务类型不能为空</p>
    </div>
  </div>

  <div class="form-item">
    <div class="form-label">
      <span class="required">*</span>巡视人员:
    </div>
    <div class="form-field">
      <el-select v-model="user" :class="{'invalid': djiUserErrors.user}" placeholder="请选择巡视人员" class="form-input" filterable
        clearable>
        <el-option
          v-for="item in filteredOrganizationsUser"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <p v-if="djiUserErrors.user" class="error-text">巡视人员不能为空</p>
    </div>
  </div>

  <div class="form-item">
    <div class="form-label">
      <span class="required">*</span>巡视日期:
    </div>
    <div class="form-field">
      <el-date-picker
        v-model="selectData"
        :disabled-date="disabledDate"
        type="dates"
        placeholder="选择日期"
        :class="{'invalid': djiUserErrors.selectData}"
        class="form-input"
      />
      <p v-if="djiUserErrors.selectData" class="error-text">巡视日期不能为空</p>
    </div>
  </div>
</div>

      <div class="dialog-header">
        <h3>巡视站点配置</h3>
        <div class="header-divider"></div>
      </div>
      
      <div class="tower-config-container">
        <div class="tower-selection">
          <div class="tower-selection-header">
            <h4>通信塔站点</h4>
          </div>
          <el-select v-model="Prefecture" placeholder="选择地市" class="full-width-select">
            <el-option
              v-for="item in Prefectures"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <div class="search-tower">
            <el-input v-model="searchTowerName" placeholder="输入通信塔站点名称" />
            <el-button type="primary" @click="filterTower">查询</el-button>
          </div>
          <div class="tree-container">
            <el-tree
              ref="leftTree"
              :data="treeData"
              show-checkbox
              :default-checked-keys="value"
              @check-change="handleCheckChange"
              :default-expand-all="true"
              node-key="value"
              class="custom-tree"
            />
          </div>
        </div>
        
        <div class="tower-selected">
          <div class="tower-selected-header">
            <h4>已选择{{ selectedCount }}个通信塔站点</h4>
          </div>
          <div class="tree-container">
            <el-tree
              :data="filteredTreeData"
              :default-checked-keys="value"
              :expand-on-click-node="true"
              :default-expand-all="true"
              node-key="value"
              class="custom-tree"
            />
          </div>
        </div>
      </div>
      
      <!-- 保存和取消按钮 -->
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="sumbitMessage()">确定</el-button>
      </div>
    </el-dialog>

    <!-- 修改任务对话框 -->
    <el-dialog 
      v-model="visibleChange" 
      :show-close="false" 
      width="800px"
      class="custom-dialog"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="dialog-header">
          <h3>巡视任务基本信息</h3>
          <div class="header-divider"></div>
        </div>
      </template>

      <!-- 输入框区域 -->
      <div class="form-container">
        <div class="form-item">
          <div class="form-label">
            <span class="required">*</span>所属机构:
          </div>
          <el-select v-model="OrganizationName" placeholder="请选择所属机构" class="form-input">
            <el-option
              v-for="item in transformedSecondaryOrganizationList"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        
        <div class="form-item">
          <div class="form-label">
            <span class="required">*</span>任务类型
          </div>
          <el-select v-model="taskAdd" placeholder="请选择任务类型" class="form-input">
            <el-option
              v-for="item in tasks"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        
        <div class="form-item">
          <div class="form-label">
            <span class="required">*</span>巡视人员
          </div>
          <el-select v-model="user" placeholder="请选择巡视人员" class="form-input">
            <el-option
              v-for="item in filteredOrganizationsUser"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <div class="form-item">
          <div class="form-label">
            <span class="required">*</span>巡视日期
          </div>
          <el-date-picker
            v-model="selectData"
            :disabled-date="disabledDate"
            type="dates"
            placeholder="选择日期"
            class="form-input"
          />
        </div>
      </div>

      <!-- <div class="dialog-header">
        <h3>巡视站点配置</h3>
        <div class="header-divider"></div>
      </div>
      
      <div class="tower-config-single">
        <el-select v-model="Prefecture" placeholder="选择地市" class="full-width-select">
          <el-option
            v-for="item in Prefectures"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select 
          v-model="towerId" 
          placeholder="请选择通信塔站点名称" 
          class="full-width-select tower-select"
        >
          <el-option
            v-for="item in filteredTowerData"
            :label="item.tower.towerName"
            :value="item.tower.id"
          />
        </el-select>
      </div> -->
      
      <!-- 保存和取消按钮 -->
      <div class="dialog-footer">
        <el-button @click="visibleChange = false">取消</el-button>
        <el-button type="primary" @click="changeMessage()">确定</el-button>
      </div>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog 
      v-model="centerDialogVisible" 
      title="警告" 
      width="500px" 
      center
      class="confirm-dialog"
    >
      <div class="confirm-content">
        <el-icon :size="30" color="#f56c6c"><CircleCloseFilled /></el-icon>
        <span>是否删除该项 "{{deleteItem.inspectionTask?.taskName}}" ?</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleClick(deleteItem.inspectionTask?.id)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus';
import { CircleCloseFilled } from '@element-plus/icons-vue';
import { ref, onMounted, computed, nextTick , onUnmounted} from 'vue'
import request from '@/utils/request';
import { useAuthStore } from '@/stores/user';
import showMessage from '@/utils/showMessage';
import { hasPermission } from '@/utils/permissionUtils';

const authStore = useAuthStore(); // 使用store仓库进行数据管理

// 数据定义
const searchTowerName = ref('') // 用于搜索通信塔名称
const originalTowerData = ref<any>([]) // 保存原始通信塔数据
const filteredTowerData = ref<any>([]) // 保存筛选后的通信塔数据
const tableData = ref([]); // 原始数据
const displayedData = ref([]); // 当前页显示的数据
const currentPage = ref(1); // 当前页码
const pageSize = ref(5); // 每页条数
const total = ref(0); // 总条数
const input = ref('')
const userName = ref('')
const passWord = ref('')
const visible = ref(false)
const visibleChange = ref(false)
const loading = ref(false)
const value = ref<(number | string)[]>([])
const selectedCount = ref(0) // 记录已选择的节点数
const selectData = ref() // 选择的日期
const user = ref() // 选择的用户
const taskAdd = ref() // 任务类型
const Prefecture = ref('阜阳市') // 地市
const city = ref()
const task = ref()
const state = ref()
const type = ref<number>()
const centerDialogVisible = ref(false)
const deleteItem = ref()
const towerId = ref()
const selectRow = ref()
const leftTree = ref<InstanceType<typeof ElTree>>(); // 获取左侧 el-tree 的引用
const selectedKeys = ref<string[]>([]); // 记录已勾选的节点 keys
const OrganizationName = ref()
const SecondaryOrganizationList = ref([])
const towerData = ref()
const towerTypeList = ref()
const userList = ref()
const allTask = ref()

const djiUserErrors = ref({
  OrganizationName: false,
  taskAdd: false,
  user: false,
  selectData: false,
});
const validateDjiUser = () => {
  let isValid = true;

  if (!OrganizationName.value) {
    djiUserErrors.value.OrganizationName = true;
    isValid = false;
  } else {
    djiUserErrors.value.OrganizationName = false;
  }

  if (!taskAdd.value) {
    djiUserErrors.value.taskAdd = true;
    isValid = false;
  } else {
    djiUserErrors.value.taskAdd = false;
  }

  if (!user.value) {
    djiUserErrors.value.user = true;
    isValid = false;
  } else {
    djiUserErrors.value.user = false;
  }

  if (!selectData.value || selectData.value.length === 0) {
    djiUserErrors.value.selectData = true;
    isValid = false;
  } else {
    djiUserErrors.value.selectData = false;
  }

  return isValid;
};

// 常量定义
const Prefectures = [
  { value: '阜阳市', label: '阜阳市' }
];

const areaOrder = [
  '颍州区', '颍东区', '颍泉区', '临泉区', '太和县', '阜南县', '颍上县', '界首市'
];

const citys = [
  { value: '颍州区', label: '颍州区' },
  { value: '颍东区', label: '颍东区' },
  { value: '颍泉区', label: '颍泉区' },
  { value: '临泉区', label: '临泉区' },
  { value: '太和县', label: '太和县' },
  { value: '阜南县', label: '阜南县' },
  { value: '颍上县', label: '颍上县' },
  { value: '界首市', label: '界首市' }
];

const tasks = [
  { value: '例行巡检', label: '例行巡检' },
  { value: '自定义巡检', label: '自定义巡检' }
];

const states = [
  { value: '未下发', label: '未下发' },
  { value: '待执行', label: '待执行' },
  { value: '执行中', label: '执行中' },
  { value: '已完成', label: '已完成' },
  { value: '执行失败', label: '执行失败' }
];

// 计算属性
const transformedSecondaryOrganizationList = computed(() => {
  return SecondaryOrganizationList.value.map((item: any) => ({
    value: item.id,
    label: item.organizationName
  }));
});

const sortedTowerData = computed(() => {
  return filteredTowerData.value?.sort((a: any, b: any) => {
    const areaA = a.tower.county;
    const areaB = b.tower.county;
    return areaOrder.indexOf(areaA) - areaOrder.indexOf(areaB);
  });
});

const treeData = computed(() => {
  const groupedData = sortedTowerData.value?.reduce((acc: any, item: any) => {
    const county = item.tower.county;
    if (!acc[county]) {
      acc[county] = [];
    }
    acc[county].push({
      value: item.tower.id,
      label: item.tower.towerName,
    });
    return acc;
  }, {});

  return groupedData ? Object.keys(groupedData).map((county) => ({
    value: county,
    label: county,
    children: groupedData[county],
  })) : [];
});

const filteredTreeData = computed(() => {
  const filteredData = filterTreeDataBySelectedKeys(treeData.value, selectedKeys.value);
  updateSelectedCount();
  return filteredData;
});

const filteredOrganizationsUser = computed(() => {
  return userList?.value?.filter((item: any) => item?.role?.roleName === '巡检员')
    .map((item: any) => ({
      value: item.user.id,
      label: item.user.name,
    }));
});

// 方法定义
const disabledDate = (time: Date) => {
  // 获取今天的开始时间（午夜00:00:00）
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  
  // 禁用今天之前的所有日期
  return time.getTime() < today.getTime();
}

const getAllSecondaryOrganization = () => {
  request.get('/user/getAllSecondaryOrganization').then((res: any) => {
    SecondaryOrganizationList.value = res.data
  })
}

const getAlltower = () => {
  request.get('/resource/getAllTower').then((res) => {
    originalTowerData.value = res.data
    filteredTowerData.value = [...res.data] // 初始时显示所有数据
    towerData.value = res.data
  })
}

// 添加筛选通信塔的方法
const filterTower = () => {
  if (!searchTowerName.value) {
    filteredTowerData.value = [...originalTowerData.value]
    return
  }
  
  filteredTowerData.value = originalTowerData.value.filter((item: any) => 
    item.tower?.towerName?.includes(searchTowerName.value)
  )
  
  // 清空已选中的节点
  selectedKeys.value = []
  if (leftTree.value) {
    leftTree.value.setCheckedKeys([])
  }
  updateSelectedCount()
}

const getAllTowerType = () => {
  request.get('/resource/getAllTowerType').then((res) => {
    towerTypeList.value = res.data
  })
}

const getAllUser = () => {
  request.get('/user/getAllUser').then((res) => {
    userList.value = res.data
  })
}

const handleCheckChange = (data: any, checked: boolean) => {
  const value = data.value;
  if (checked) {
    selectedKeys.value.push(value);
  } else {
    selectedKeys.value = selectedKeys.value.filter((key: string) => key !== value);
  }
  updateSelectedCount();
};

const updateSelectedCount = () => {
  if (!treeData.value) return;
  
  let count = 0;
  treeData.value.forEach((region: any) => {
    if (region.children) {
      region.children.forEach((tower: any) => {
        if (selectedKeys.value.includes(tower.value)) {
          count++;
        }
      });
    }
  });
  selectedCount.value = count;
};

const filterTreeDataBySelectedKeys = (treeData: any, selectedKeys: any) => {
  return treeData?.map((node: any) => {
    if (selectedKeys.includes(node.value)) {
      return {
        ...node,
        children: node.children || [],
      };
    } else if (node.children) {
      const filteredChildren = node.children.filter((child: any) => selectedKeys.includes(child.value));
      if (filteredChildren.length > 0) {
        return {
          ...node,
          children: filteredChildren,
        };
      }
      return null;
    }
    return null;
  }).filter((node: any) => node !== null) || [];
};

const removeNode = (data: any) => {
  selectedKeys.value = selectedKeys.value.filter((key: string) => key !== data.value);
  if (leftTree.value) {
    leftTree.value.setCheckedKeys(selectedKeys.value);
  }
  updateSelectedCount();
};

const extractChildrenFromTree = (treeData: any) => {
  const children: any = [];
  treeData?.forEach((node: any) => {
    if (node.children && node.children.length > 0) {
      node.children.forEach((child: any) => {
        children.push(child);
      });
    }
  });
  return children;
};

const filterUser = () => {
  request.post("/inspection/getInspectionTaskByCondition", {
    city: Prefecture.value || '',
    county: city.value || '',
    taskType: task.value || '',
    taskStatus: state.value || '',
    towerTypeID: type.value || '',
    taskName: input.value || ''
  }).then((res) => {
    if (res.status == 200) {
      tableData.value = res.data;
      total.value = res.data.length;
      updateDisplayedData();
    }
  });
};

const showDialog = (item: any) => {
  centerDialogVisible.value = true
  deleteItem.value = item
}

const handleClick = (id: any) => {
  request.post("/inspection/deleteInspectionTaskByID", { id }).then((res) => {
    if (res.data.status == 'success') {
      request.post('/user/insertOperation', {
        username: authStore.user?.username,
        name: authStore.user?.name,
        organizationID: authStore.organizationID,
        ip: null,
        operationModel: "任务追踪",
        operationResult: "删除任务",
        operationTime: null,
        operationType: "operation"
      })
      getAllTask()
      centerDialogVisible.value = false
    }
  })
}

const changeTask = (row: any) => {
  selectRow.value = row
  visibleChange.value = true
  OrganizationName.value = row.inspectionTask.organizationID;
  taskAdd.value = row.inspectionTask.taskType;
  user.value = row.user.id;
  Prefecture.value = row.Prefecture;
  input.value = row.input;
  towerId.value = row.tower.id;
}

const changeMessage = () => {
  const task = selectRow.value
  request.post('/inspection/updateInspectionTask', {
    id: task.inspectionTask.id,
    taskType: task.inspectionTask.taskType,
    inspectionDate: formatDate(selectData.value),
    organizationID: task.inspectionTask.organizationID,
    userID: task.inspectionTask.userID,
  }).then((res: any) => {
    showMessage(res)
    if (res.data.status === 'success') {
      getAllTask()
      visibleChange.value = false
    }
  })
}

const formatDate = (date: any) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const newUser = () => {
  djiUserErrors.value ={
  OrganizationName: false,
  taskAdd: false,
  user: false,
  selectData: false,
};
  visible.value = true;
  OrganizationName.value = ''
  taskAdd.value = ''
  user.value = ''
  selectData.value = ''
  nextTick(() => {
    if (leftTree.value) {
      leftTree.value.setCheckedKeys([]); // 清除所有勾选
    }
    selectedKeys.value = []; // 清空已选keys
    value.value = []; // 清空value
    selectedCount.value = 0; // 重置计数
  });
}

const sumbitMessage = () => {
  if (!validateDjiUser()) return;
  const filteredTreeData = filterTreeDataBySelectedKeys(treeData.value, selectedKeys.value);
  const childNodes = extractChildrenFromTree(filteredTreeData);
  const nodeIds = childNodes.map((node: any) => node.value);
  if (nodeIds.length === 0) {
    console.error("No tower IDs selected");
    showMessage({ data: { status: 'error', message: '请至少选择一个塔后建立任务' } });
    return;
  }
  const formData = new FormData()
  formData.append('taskType', taskAdd.value)
  formData.append('inspectionDate', formatDate(selectData.value))
  formData.append('organizationID', OrganizationName.value)
  formData.append('userID', user.value)
  formData.append('towerIDs', nodeIds)
  

  request.post("/inspection/insertInspectionTask", formData).then((res: any) => {
    showMessage(res)
    if (res.data.status === 'success') {
      visible.value = false;
      nextTick(() => {
        getAllTask()
      });
    }
  })
}

const getAllTask = () => {
  request.get('/inspection/getAllInspectionTask').then((res) => {
    tableData.value = res.data
    total.value = res.data.length;
    updateDisplayedData()
  })
}

const updateDisplayedData = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  const currentData = tableData.value.slice(start, end);
  displayedData.value = Array.from({ length: pageSize.value }, (_, index) => currentData[index] || {});
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  updateDisplayedData();
};

const getStatusTagType = (status: string) => {
  switch (status) {
    case '已完成': return 'success';
    case '执行中': return 'warning';
    case '执行失败': return 'danger';
    case '待执行': return 'info';
    default: return '';
  }
}

const handleRowClick = (row: any) => {
  // 行点击事件处理
}

// 生命周期钩子

const detectPageSize = () => {
  const width = window.innerWidth;
  pageSize.value = width <= 1800 ? 5 : 20; // ≤1200px 时显示10条，>1200px 时显示20条
  updateDisplayedData();
};

  onMounted(()=>{
    detectPageSize(); // 初始调用
    window.addEventListener('resize', detectPageSize); // 直接监听resize事件，不使用防抖
    getAllUser()
    getAllSecondaryOrganization()
    getAlltower()
    getAllTask()
    getAllTowerType()
  })
  onUnmounted(() => {
  window.removeEventListener('resize', detectPageSize); // 移除事件监听
});
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  padding: 10px;
  background-color: #f5f7fa;
  overflow: hidden; /* 让圆角生效 */
  box-sizing: border-box;
}

/* 搜索区域样式 */
.search-area {
  background-color: #fff;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-item {
  width: 200px;
  margin-right: 15px;
}

.search-row {
  display: flex;
  align-items: center;
  margin-top: 15px;
}

.search-input {
  width: 240px;
  margin-right: 15px;
}

.search-btn {
  width: 120px;
  margin-right: 15px;
}

/* 表格容器样式 */
.table-container {
  background-color: #fff;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  min-height: calc(100vh - 400px);
}


  .table-text {
  color: #606266;
  word-break: break-word;   /* 避免长英文单词或URL撑破容器 */
  white-space: normal;      /* 正常换行 */
  line-height: 22px;
}

.action-buttons {
  display: flex;
  justify-content: center;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 对话框样式 */
.custom-dialog {
  border-radius: 8px;
}

.dialog-header {
  padding-bottom: 15px;
}

.dialog-header h3 {
  margin: 0;
  color: #409eff;
  font-size: 18px;
}

.header-divider {
  height: 1px;
  background: linear-gradient(to right, #409eff, #dcdfe6);
  margin-top: 10px;
}

.form-container {
  padding: 0 20px;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.form-label {
  width: 100px;
  text-align: right;
  margin-right: 15px;
  color: #606266;
}

.required {
  color: #f56c6c;
  margin-right: 5px;
}

.form-input {
  flex: 1;
}

/* 通信塔配置区域 */
.tower-config-container {
  display: flex;
  margin: 20px 0;
  background-color: #f8fafc;
  border-radius: 8px;
  overflow: hidden;
}

.tower-selection, .tower-selected {
  width: 50%;
  padding: 15px;
}

.tower-selection-header, .tower-selected-header {
  text-align: center;
  margin-bottom: 15px;
}

.tower-selection-header h4, .tower-selected-header h4 {
  margin: 0;
  color: #409eff;
}

.search-tower {
  display: flex;
  margin: 15px 0;
}

.search-tower .el-input {
  flex: 1;
  margin-right: 10px;
}

.tree-container {
  height: 300px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  overflow-y: auto;
}

.custom-tree {
  :deep(.el-tree-node__content) {
    height: 36px;
  }
}

.tower-config-single {
  padding: 0 20px;
}

.full-width-select {
  width: 100%;
  margin-bottom: 15px;
}

.tower-select {
  margin-top: 15px;
}

/* 对话框底部按钮 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

/* 确认对话框样式 */
.confirm-dialog {
  .confirm-content {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
    
    .el-icon {
      margin-right: 10px;
    }
    
    span {
      font-size: 16px;
    }
  }
}

/* 过渡效果 */
.el-button {
  transition: all 0.3s;
}

.el-table {
  :deep(.el-table__row) {
    transition: background-color 0.3s;
    
    &:hover {
      background-color: #f5f7fa !important;
    }
  }
}

@media (max-width: 1200px) {
  .search-row,
  .search-area,
  .form-container,
  .tower-config-container {
    flex-direction: column !important;
  }

  .search-item,
  .search-input,
  .search-btn {
    width: 100% !important;
    margin: 8px 0 !important;
  }

  .tower-selection,
  .tower-selected {
    width: 100% !important;
  }

  .action-buttons {
    flex-direction: column;
  }

  .dialog-footer {
    flex-direction: column;
    align-items: stretch;
  }

  .dialog-footer .el-button {
    margin-top: 10px;
  }
}

@media (max-width: 768px) {
  .table-container {
    overflow-x: auto;
  }

  .el-table {
    min-width: 800px; /* 防止列堆叠 */
  }

  .search-area {
    padding: 10px;
  }

  .form-label {
    width: 100%;
    text-align: left;
    margin-bottom: 5px;
  }

  .form-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .form-input {
    width: 100%;
  }
}




/* 表格样式修改 */
/* 表格自动宽度样式 */
.auto-width-table {
  table-layout: fixed; /* 关键属性 */
}

/* 定义各列宽度比例 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(1)) { width: 5%; }  /* 序号 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(2)) { width: 12%; } /* 任务名称 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(3)) { width: 12%; } /* 任务类型 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(4)) { width: 12%; } /* 通信塔类型 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(5)) { width: 8%; }  /* 地市 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(6)) { width: 8%; }  /* 区县 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(7)) { width: 8%; }  /* 巡视人员 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(8)) { width: 12%; } /* 任务状态 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(9)) { width: 15%; } /* 创建时间 */
.auto-width-table :deep(.el-table__header-wrapper th:nth-child(10)) { width: 8%; } /* 操作 */

/* 确保内容不溢出 */
.auto-width-table :deep(.cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .auto-width-table {
    min-width: 1000px; /* 在小屏幕上保持水平滚动 */
  }
}

.invalid {
  border: 1px solid #f56c6c !important;
  border-radius: 4px;
}
.error-text {
  color: #f56c6c;
  font-size: 13px;
  margin-top: 4px;
  margin-left: 5px;
}
.form-field {
  flex: 1;
  display: flex;
  flex-direction: column;
}
</style>